import 'base_generator.dart';
import 'page_generator.dart';
import 'controller_generator.dart';
import 'model_generator.dart';
import 'service_generator.dart';

/// 模块生成器 - 生成完整的功能模块
class ModuleGenerator extends BaseGenerator {
  static void generate(String name, Map<String, dynamic> options) {
    if (!BaseGenerator.isValidName(name)) {
      BaseGenerator.printError('模块名称格式不正确: $name');
      return;
    }

    final bool isFull = options['full'] == true;
    final bool isSimple = options['simple'] == true;
    final bool withApi = options['with-api'] == true;

    final String moduleName = BaseGenerator.toSnakeCase(name);
    final String className = BaseGenerator.toPascalCase(name);
    
    print('🚀 开始生成模块: $className');
    print('📁 模块类型: ${isFull ? '完整模块' : (isSimple ? '简单模块' : '标准模块')}');
    
    _createModuleStructure(moduleName, isFull, isSimple);
    
    if (isFull) {
      _generateFullModule(className, moduleName, withApi);
    } else if (isSimple) {
      _generateSimpleModule(className, moduleName);
    } else {
      _generateStandardModule(className, moduleName, withApi);
    }
    
    _generateModuleReadme(className, moduleName, isFull, isSimple, withApi);
    
    BaseGenerator.printSuccess('模块', className, 'lib/features/$moduleName');
    _printModuleStructure(moduleName, isFull, isSimple);
    _printUsageInstructions(className, moduleName, isFull, isSimple, withApi);
  }

  /// 创建模块目录结构
  static void _createModuleStructure(String moduleName, bool isFull, bool isSimple) {
    final String basePath = 'lib/features/$moduleName';
    
    if (isFull) {
      // Clean Architecture 完整结构
      BaseGenerator.createDirectoryIfNotExists('$basePath/data/datasources');
      BaseGenerator.createDirectoryIfNotExists('$basePath/data/models');
      BaseGenerator.createDirectoryIfNotExists('$basePath/data/repositories');
      BaseGenerator.createDirectoryIfNotExists('$basePath/domain/entities');
      BaseGenerator.createDirectoryIfNotExists('$basePath/domain/repositories');
      BaseGenerator.createDirectoryIfNotExists('$basePath/domain/usecases');
      BaseGenerator.createDirectoryIfNotExists('$basePath/presentation/controllers');
      BaseGenerator.createDirectoryIfNotExists('$basePath/presentation/pages');
      BaseGenerator.createDirectoryIfNotExists('$basePath/presentation/widgets');
    } else if (isSimple) {
      // 简单结构
      BaseGenerator.createDirectoryIfNotExists('$basePath/pages');
      BaseGenerator.createDirectoryIfNotExists('$basePath/models');
    } else {
      // 标准结构
      BaseGenerator.createDirectoryIfNotExists('$basePath/presentation/controllers');
      BaseGenerator.createDirectoryIfNotExists('$basePath/presentation/pages');
      BaseGenerator.createDirectoryIfNotExists('$basePath/presentation/widgets');
      BaseGenerator.createDirectoryIfNotExists('$basePath/data/models');
      BaseGenerator.createDirectoryIfNotExists('$basePath/data/services');
    }
  }

  /// 生成完整模块 (Clean Architecture)
  static void _generateFullModule(String className, String moduleName, bool withApi) {
    final String basePath = 'lib/features/$moduleName';
    
    // 1. 实体层 (Domain/Entities)
    _generateEntity(className, basePath);
    
    // 2. 仓库接口 (Domain/Repositories)
    _generateRepositoryInterface(className, basePath);
    
    // 3. 用例 (Domain/UseCases)
    _generateUseCases(className, basePath);
    
    // 4. 数据模型 (Data/Models)
    _generateDataModel(className, basePath);
    
    // 5. 数据源 (Data/DataSources)
    _generateDataSources(className, basePath, withApi);
    
    // 6. 仓库实现 (Data/Repositories)
    _generateRepositoryImplementation(className, basePath);
    
    // 7. 控制器 (Presentation/Controllers)
    _generateModuleController(className, basePath, true);
    
    // 8. 页面 (Presentation/Pages)
    _generateModulePage(className, basePath, true);
    
    // 9. 组件 (Presentation/Widgets)
    _generateModuleWidgets(className, basePath);
  }

  /// 生成简单模块
  static void _generateSimpleModule(String className, String moduleName) {
    final String basePath = 'lib/features/$moduleName';
    
    // 1. 简单模型
    final String modelPath = '$basePath/models/${BaseGenerator.toSnakeCase(className)}.dart';
    final String modelContent = _generateSimpleModel(className);
    BaseGenerator.writeFile(modelPath, modelContent);
    
    // 2. 简单页面
    final String pagePath = '$basePath/pages/${BaseGenerator.toSnakeCase(className)}_page.dart';
    final String pageContent = _generateSimplePage(className);
    BaseGenerator.writeFile(pagePath, pageContent);
  }

  /// 生成标准模块
  static void _generateStandardModule(String className, String moduleName, bool withApi) {
    final String basePath = 'lib/features/$moduleName';
    
    // 1. 数据模型
    final String modelPath = '$basePath/data/models/${BaseGenerator.toSnakeCase(className)}.dart';
    ModelGenerator.generate(className, {'module': moduleName, 'with-json': true});
    
    // 2. 服务层
    if (withApi) {
      ServiceGenerator.generate('${className}Service', {
        'module': moduleName,
        'with-api': true,
        'with-storage': true
      });
    }
    
    // 3. 控制器
    _generateModuleController(className, basePath, false);
    
    // 4. 页面
    _generateModulePage(className, basePath, false);
  }

  // ===== 完整模块生成方法 =====
  
  static void _generateEntity(String className, String basePath) {
    final String content = BaseGenerator.generateFileHeader(
      '${className}Entity',
      '${className}实体类'
    ) + '''
abstract class ${className}Entity {
  final String id;
  final String name;
  final String description;
  final DateTime createdAt;
  final DateTime updatedAt;

  const ${className}Entity({
    required this.id,
    required this.name,
    required this.description,
    required this.createdAt,
    required this.updatedAt,
  });

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;
    return other is ${className}Entity && other.id == id;
  }

  @override
  int get hashCode => id.hashCode;

  @override
  String toString() => '${className}Entity{id: \$id, name: \$name}';
}
''';
    
    BaseGenerator.writeFile('$basePath/domain/entities/${BaseGenerator.toSnakeCase(className)}_entity.dart', content);
  }

  static void _generateRepositoryInterface(String className, String basePath) {
    final String content = BaseGenerator.generateFileHeader(
      '${className}Repository',
      '${className}仓库接口'
    ) + '''
import '../entities/${BaseGenerator.toSnakeCase(className)}_entity.dart';

abstract class ${className}Repository {
  Future<List<${className}Entity>> getAll();
  Future<${className}Entity?> getById(String id);
  Future<${className}Entity> create(${className}Entity entity);
  Future<${className}Entity> update(${className}Entity entity);
  Future<bool> delete(String id);
  Future<List<${className}Entity>> search(String query);
}
''';
    
    BaseGenerator.writeFile('$basePath/domain/repositories/${BaseGenerator.toSnakeCase(className)}_repository.dart', content);
  }

  static void _generateUseCases(String className, String basePath) {
    final List<String> useCases = [
      'Get${className}List',
      'Get${className}ById',
      'Create$className',
      'Update$className',
      'Delete$className'
    ];

    for (final useCase in useCases) {
      final String content = BaseGenerator.generateFileHeader(
        useCase,
        '$useCase用例'
      ) + '''
import '../entities/${BaseGenerator.toSnakeCase(className)}_entity.dart';
import '../repositories/${BaseGenerator.toSnakeCase(className)}_repository.dart';

class $useCase {
  final ${className}Repository repository;

  $useCase(this.repository);

  ${_generateUseCaseMethod(useCase, className)}
}
''';
      
      BaseGenerator.writeFile('$basePath/domain/usecases/${BaseGenerator.toSnakeCase(useCase)}.dart', content);
    }
  }

  static String _generateUseCaseMethod(String useCase, String className) {
    switch (useCase) {
      case 'Get${className}List':
        return 'Future<List<${className}Entity>> call() => repository.getAll();';
      case 'Get${className}ById':
        return 'Future<${className}Entity?> call(String id) => repository.getById(id);';
      case 'Create$className':
        return 'Future<${className}Entity> call(${className}Entity entity) => repository.create(entity);';
      case 'Update$className':
        return 'Future<${className}Entity> call(${className}Entity entity) => repository.update(entity);';
      case 'Delete$className':
        return 'Future<bool> call(String id) => repository.delete(id);';
      default:
        return 'Future<void> call() async {}';
    }
  }

  static void _generateDataModel(String className, String basePath) {
    final String content = BaseGenerator.generateFileHeader(
      '${className}Model',
      '${className}数据模型'
    ) + '''
import '../../domain/entities/${BaseGenerator.toSnakeCase(className)}_entity.dart';

class ${className}Model extends ${className}Entity {
  const ${className}Model({
    required String id,
    required String name,
    required String description,
    required DateTime createdAt,
    required DateTime updatedAt,
  }) : super(
          id: id,
          name: name,
          description: description,
          createdAt: createdAt,
          updatedAt: updatedAt,
        );

  factory ${className}Model.fromJson(Map<String, dynamic> json) {
    return ${className}Model(
      id: json['id'] as String,
      name: json['name'] as String,
      description: json['description'] as String,
      createdAt: DateTime.parse(json['created_at'] as String),
      updatedAt: DateTime.parse(json['updated_at'] as String),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'description': description,
      'created_at': createdAt.toIso8601String(),
      'updated_at': updatedAt.toIso8601String(),
    };
  }

  ${className}Model copyWith({
    String? id,
    String? name,
    String? description,
    DateTime? createdAt,
    DateTime? updatedAt,
  }) {
    return ${className}Model(
      id: id ?? this.id,
      name: name ?? this.name,
      description: description ?? this.description,
      createdAt: createdAt ?? this.createdAt,
      updatedAt: updatedAt ?? this.updatedAt,
    );
  }
}
''';
    
    BaseGenerator.writeFile('$basePath/data/models/${BaseGenerator.toSnakeCase(className)}_model.dart', content);
  }

  static void _generateDataSources(String className, String basePath, bool withApi) {
    if (withApi) {
      // 远程数据源
      final String remoteContent = BaseGenerator.generateFileHeader(
        '${className}RemoteDataSource',
        '${className}远程数据源'
      ) + '''
import 'package:dio/dio.dart';
import '../models/${BaseGenerator.toSnakeCase(className)}_model.dart';
import '../../../core/network/dio_client.dart';

abstract class ${className}RemoteDataSource {
  Future<List<${className}Model>> getAll();
  Future<${className}Model?> getById(String id);
  Future<${className}Model> create(${className}Model model);
  Future<${className}Model> update(${className}Model model);
  Future<bool> delete(String id);
}

class ${className}RemoteDataSourceImpl implements ${className}RemoteDataSource {
  final DioClient _dioClient;
  static const String _endpoint = '/${BaseGenerator.toKebabCase(className)}s';

  ${className}RemoteDataSourceImpl(this._dioClient);

  @override
  Future<List<${className}Model>> getAll() async {
    final response = await _dioClient.get(_endpoint);
    final List<dynamic> data = response.data['data'];
    return data.map((json) => ${className}Model.fromJson(json)).toList();
  }

  @override
  Future<${className}Model?> getById(String id) async {
    final response = await _dioClient.get('\$_endpoint/\$id');
    return ${className}Model.fromJson(response.data['data']);
  }

  @override
  Future<${className}Model> create(${className}Model model) async {
    final response = await _dioClient.post(_endpoint, data: model.toJson());
    return ${className}Model.fromJson(response.data['data']);
  }

  @override
  Future<${className}Model> update(${className}Model model) async {
    final response = await _dioClient.put('\$_endpoint/\${model.id}', data: model.toJson());
    return ${className}Model.fromJson(response.data['data']);
  }

  @override
  Future<bool> delete(String id) async {
    await _dioClient.delete('\$_endpoint/\$id');
    return true;
  }
}
''';
      
      BaseGenerator.writeFile('$basePath/data/datasources/${BaseGenerator.toSnakeCase(className)}_remote_datasource.dart', remoteContent);
    }

    // 本地数据源
    final String localContent = BaseGenerator.generateFileHeader(
      '${className}LocalDataSource',
      '${className}本地数据源'
    ) + '''
import '../models/${BaseGenerator.toSnakeCase(className)}_model.dart';
import '../../../core/storage/storage_service.dart';

abstract class ${className}LocalDataSource {
  Future<List<${className}Model>> getAll();
  Future<${className}Model?> getById(String id);
  Future<void> save(${className}Model model);
  Future<void> saveAll(List<${className}Model> models);
  Future<bool> delete(String id);
  Future<void> clear();
}

class ${className}LocalDataSourceImpl implements ${className}LocalDataSource {
  final StorageService _storageService;
  static const String _key = '${BaseGenerator.toSnakeCase(className)}_list';

  ${className}LocalDataSourceImpl(this._storageService);

  @override
  Future<List<${className}Model>> getAll() async {
    final List<dynamic>? data = await _storageService.read(_key);
    if (data == null) return [];
    return data.map((json) => ${className}Model.fromJson(json)).toList();
  }

  @override
  Future<${className}Model?> getById(String id) async {
    final List<${className}Model> all = await getAll();
    try {
      return all.firstWhere((item) => item.id == id);
    } catch (e) {
      return null;
    }
  }

  @override
  Future<void> save(${className}Model model) async {
    final List<${className}Model> all = await getAll();
    final index = all.indexWhere((item) => item.id == model.id);
    
    if (index != -1) {
      all[index] = model;
    } else {
      all.add(model);
    }
    
    await saveAll(all);
  }

  @override
  Future<void> saveAll(List<${className}Model> models) async {
    final data = models.map((model) => model.toJson()).toList();
    await _storageService.write(_key, data);
  }

  @override
  Future<bool> delete(String id) async {
    final List<${className}Model> all = await getAll();
    final initialLength = all.length;
    all.removeWhere((item) => item.id == id);
    
    if (all.length != initialLength) {
      await saveAll(all);
      return true;
    }
    return false;
  }

  @override
  Future<void> clear() async {
    await _storageService.delete(_key);
  }
}
''';
    
    BaseGenerator.writeFile('$basePath/data/datasources/${BaseGenerator.toSnakeCase(className)}_local_datasource.dart', localContent);
  }

  static void _generateRepositoryImplementation(String className, String basePath) {
    final String content = BaseGenerator.generateFileHeader(
      '${className}RepositoryImpl',
      '${className}仓库实现'
    ) + '''
import '../../domain/entities/${BaseGenerator.toSnakeCase(className)}_entity.dart';
import '../../domain/repositories/${BaseGenerator.toSnakeCase(className)}_repository.dart';
import '../datasources/${BaseGenerator.toSnakeCase(className)}_local_datasource.dart';
import '../datasources/${BaseGenerator.toSnakeCase(className)}_remote_datasource.dart';
import '../models/${BaseGenerator.toSnakeCase(className)}_model.dart';

class ${className}RepositoryImpl implements ${className}Repository {
  final ${className}RemoteDataSource? _remoteDataSource;
  final ${className}LocalDataSource _localDataSource;

  ${className}RepositoryImpl({
    ${className}RemoteDataSource? remoteDataSource,
    required ${className}LocalDataSource localDataSource,
  })  : _remoteDataSource = remoteDataSource,
        _localDataSource = localDataSource;

  @override
  Future<List<${className}Entity>> getAll() async {
    try {
      // 尝试从远程获取数据
      if (_remoteDataSource != null) {
        final remoteData = await _remoteDataSource!.getAll();
        await _localDataSource.saveAll(remoteData);
        return remoteData;
      }
    } catch (e) {
      // 远程失败，使用本地数据
      print('远程数据获取失败，使用本地数据: \$e');
    }
    
    return await _localDataSource.getAll();
  }

  @override
  Future<${className}Entity?> getById(String id) async {
    try {
      if (_remoteDataSource != null) {
        final remoteData = await _remoteDataSource!.getById(id);
        if (remoteData != null) {
          await _localDataSource.save(remoteData);
          return remoteData;
        }
      }
    } catch (e) {
      print('远程数据获取失败: \$e');
    }
    
    return await _localDataSource.getById(id);
  }

  @override
  Future<${className}Entity> create(${className}Entity entity) async {
    final model = _entityToModel(entity);
    
    try {
      if (_remoteDataSource != null) {
        final remoteResult = await _remoteDataSource!.create(model);
        await _localDataSource.save(remoteResult);
        return remoteResult;
      }
    } catch (e) {
      print('远程创建失败: \$e');
    }
    
    await _localDataSource.save(model);
    return model;
  }

  @override
  Future<${className}Entity> update(${className}Entity entity) async {
    final model = _entityToModel(entity);
    
    try {
      if (_remoteDataSource != null) {
        final remoteResult = await _remoteDataSource!.update(model);
        await _localDataSource.save(remoteResult);
        return remoteResult;
      }
    } catch (e) {
      print('远程更新失败: \$e');
    }
    
    await _localDataSource.save(model);
    return model;
  }

  @override
  Future<bool> delete(String id) async {
    try {
      if (_remoteDataSource != null) {
        await _remoteDataSource!.delete(id);
      }
    } catch (e) {
      print('远程删除失败: \$e');
    }
    
    return await _localDataSource.delete(id);
  }

  @override
  Future<List<${className}Entity>> search(String query) async {
    final List<${className}Entity> all = await getAll();
    return all.where((entity) => 
        entity.name.toLowerCase().contains(query.toLowerCase()) ||
        entity.description.toLowerCase().contains(query.toLowerCase())
    ).toList();
  }

  ${className}Model _entityToModel(${className}Entity entity) {
    return ${className}Model(
      id: entity.id,
      name: entity.name,
      description: entity.description,
      createdAt: entity.createdAt,
      updatedAt: entity.updatedAt,
    );
  }
}
''';
    
    BaseGenerator.writeFile('$basePath/data/repositories/${BaseGenerator.toSnakeCase(className)}_repository_impl.dart', content);
  }

  static void _generateModuleController(String className, String basePath, bool isFullModule) {
    final String content = BaseGenerator.generateFileHeader(
      '${className}Controller',
      '${className}模块控制器'
    ) + '''
import 'package:get/get.dart';
${isFullModule ? '''import '../../domain/entities/${BaseGenerator.toSnakeCase(className)}_entity.dart';
import '../../domain/usecases/get_${BaseGenerator.toSnakeCase(className)}_list.dart';
import '../../domain/usecases/get_${BaseGenerator.toSnakeCase(className)}_by_id.dart';
import '../../domain/usecases/create_${BaseGenerator.toSnakeCase(className)}.dart';
import '../../domain/usecases/update_${BaseGenerator.toSnakeCase(className)}.dart';
import '../../domain/usecases/delete_${BaseGenerator.toSnakeCase(className)}.dart';''' : '''import '../data/models/${BaseGenerator.toSnakeCase(className)}.dart';'''}

class ${className}Controller extends GetxController {
  // 响应式状态
  final _isLoading = false.obs;
  final _items = <${isFullModule ? '${className}Entity' : className}>[].obs;
  final _selectedItem = Rx<${isFullModule ? '${className}Entity' : className}?>(null);
  final _errorMessage = ''.obs;

${isFullModule ? '''  // 用例
  late final Get${className}List _get${className}List;
  late final Get${className}ById _get${className}ById;
  late final Create$className _create$className;
  late final Update$className _update$className;
  late final Delete$className _delete$className;''' : ''}

  // Getters
  bool get isLoading => _isLoading.value;
  List<${isFullModule ? '${className}Entity' : className}> get items => _items;
  ${isFullModule ? '${className}Entity' : className}? get selectedItem => _selectedItem.value;
  String get errorMessage => _errorMessage.value;
  bool get hasError => _errorMessage.value.isNotEmpty;
  bool get hasItems => _items.isNotEmpty;

  @override
  void onInit() {
    super.onInit();
    _initController();
  }

  void _initController() {
${isFullModule ? '''    // 注入用例
    _get${className}List = Get.find<Get${className}List>();
    _get${className}ById = Get.find<Get${className}ById>();
    _create$className = Get.find<Create$className>();
    _update$className = Get.find<Update$className>();
    _delete$className = Get.find<Delete$className>();''' : ''}
    
    // 加载初始数据
    loadItems();
  }

  /// 加载数据列表
  Future<void> loadItems() async {
    try {
      _setLoading(true);
      _clearError();
      
${isFullModule ? '''      final items = await _get${className}List();
      _items.assignAll(items);''' : '''      // 模拟数据加载
      await Future.delayed(const Duration(seconds: 1));
      _items.assignAll([
        $className(
          id: '1',
          name: '示例项目1',
          description: '这是一个示例项目',
          createdAt: DateTime.now(),
        ),
        $className(
          id: '2', 
          name: '示例项目2',
          description: '这是另一个示例项目',
          createdAt: DateTime.now(),
        ),
      ]);'''}
      
    } catch (e) {
      _setError('加载数据失败: \$e');
    } finally {
      _setLoading(false);
    }
  }

  /// 根据ID获取项目
  Future<void> getItemById(String id) async {
    try {
      _setLoading(true);
      _clearError();
      
${isFullModule ? '''      final item = await _get${className}ById(id);
      _selectedItem.value = item;''' : '''      final item = _items.firstWhereOrNull((item) => item.id == id);
      _selectedItem.value = item;'''}
      
    } catch (e) {
      _setError('获取项目失败: \$e');
    } finally {
      _setLoading(false);
    }
  }

  /// 创建新项目
  Future<void> createItem(${isFullModule ? '${className}Entity' : className} item) async {
    try {
      _setLoading(true);
      _clearError();
      
${isFullModule ? '''      final newItem = await _create$className(item);
      _items.add(newItem);''' : '''      _items.add(item);'''}
      
      Get.snackbar('成功', '创建成功');
      
    } catch (e) {
      _setError('创建失败: \$e');
    } finally {
      _setLoading(false);
    }
  }

  /// 更新项目
  Future<void> updateItem(${isFullModule ? '${className}Entity' : className} item) async {
    try {
      _setLoading(true);
      _clearError();
      
${isFullModule ? '''      final updatedItem = await _update$className(item);
      final index = _items.indexWhere((i) => i.id == updatedItem.id);
      if (index != -1) {
        _items[index] = updatedItem;
      }''' : '''      final index = _items.indexWhere((i) => i.id == item.id);
      if (index != -1) {
        _items[index] = item;
      }'''}
      
      Get.snackbar('成功', '更新成功');
      
    } catch (e) {
      _setError('更新失败: \$e');
    } finally {
      _setLoading(false);
    }
  }

  /// 删除项目
  Future<void> deleteItem(String id) async {
    try {
      _setLoading(true);
      _clearError();
      
${isFullModule ? '''      await _delete$className(id);''' : ''}      _items.removeWhere((item) => item.id == id);
      
      if (_selectedItem.value?.id == id) {
        _selectedItem.value = null;
      }
      
      Get.snackbar('成功', '删除成功');
      
    } catch (e) {
      _setError('删除失败: \$e');
    } finally {
      _setLoading(false);
    }
  }

  /// 搜索项目
  void searchItems(String query) {
    if (query.isEmpty) {
      loadItems();
      return;
    }
    
    final filtered = _items.where((item) =>
        item.name.toLowerCase().contains(query.toLowerCase()) ||
        item.description.toLowerCase().contains(query.toLowerCase())).toList();
    
    _items.assignAll(filtered);
  }

  /// 选择项目
  void selectItem(${isFullModule ? '${className}Entity' : className}? item) {
    _selectedItem.value = item;
  }

  /// 清除选择
  void clearSelection() {
    _selectedItem.value = null;
  }

  /// 刷新数据
  Future<void> refresh() async {
    await loadItems();
  }

  /// 设置加载状态
  void _setLoading(bool loading) {
    _isLoading.value = loading;
  }

  /// 设置错误信息
  void _setError(String error) {
    _errorMessage.value = error;
    if (error.isNotEmpty) {
      Get.snackbar('错误', error);
    }
  }

  /// 清除错误
  void _clearError() {
    _errorMessage.value = '';
  }

  /// 重试操作
  void retry() {
    _clearError();
    loadItems();
  }

  @override
  void onClose() {
    // 清理资源
    super.onClose();
  }
}
''';
    
    BaseGenerator.writeFile('$basePath/presentation/controllers/${BaseGenerator.toSnakeCase(className)}_controller.dart', content);
  }

  static void _generateModulePage(String className, String basePath, bool isFullModule) {
    final String content = BaseGenerator.generateFileHeader(
      '${className}Page',
      '${className}模块主页面'
    ) + '''
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../controllers/${BaseGenerator.toSnakeCase(className)}_controller.dart';
${isFullModule ? "import '../../domain/entities/${BaseGenerator.toSnakeCase(className)}_entity.dart';" : "import '../data/models/${BaseGenerator.toSnakeCase(className)}.dart';"}

class ${className}Page extends StatelessWidget {
  const ${className}Page({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final controller = Get.put(${className}Controller());
    
    return Scaffold(
      appBar: AppBar(
        title: const Text('$className'),
        centerTitle: true,
        actions: [
          IconButton(
            icon: const Icon(Icons.search),
            onPressed: () => _showSearchDialog(context, controller),
          ),
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: controller.refresh,
          ),
        ],
      ),
      body: GetBuilder<${className}Controller>(
        builder: (controller) {
          if (controller.isLoading) {
            return const Center(
              child: CircularProgressIndicator(),
            );
          }

          if (controller.hasError) {
            return _buildErrorWidget(controller);
          }

          if (!controller.hasItems) {
            return _buildEmptyWidget();
          }

          return RefreshIndicator(
            onRefresh: controller.refresh,
            child: ListView.builder(
              padding: EdgeInsets.all(16.w),
              itemCount: controller.items.length,
              itemBuilder: (context, index) {
                final item = controller.items[index];
                return _buildItemCard(item, controller);
              },
            ),
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => _showCreateDialog(context, controller),
        child: const Icon(Icons.add),
      ),
    );
  }

  Widget _buildItemCard(${isFullModule ? '${className}Entity' : className} item, ${className}Controller controller) {
    return Card(
      margin: EdgeInsets.only(bottom: 12.h),
      child: ListTile(
        title: Text(
          item.name,
          style: TextStyle(
            fontSize: 16.sp,
            fontWeight: FontWeight.bold,
          ),
        ),
        subtitle: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              item.description,
              style: TextStyle(fontSize: 14.sp),
            ),
            SizedBox(height: 4.h),
            Text(
              '创建时间: \${_formatDate(item.createdAt)}',
              style: TextStyle(
                fontSize: 12.sp,
                color: Colors.grey[600],
              ),
            ),
          ],
        ),
        trailing: PopupMenuButton<String>(
          onSelected: (value) {
            switch (value) {
              case 'edit':
                _showEditDialog(Get.context!, controller, item);
                break;
              case 'delete':
                _showDeleteConfirmation(Get.context!, controller, item);
                break;
            }
          },
          itemBuilder: (context) => [
            const PopupMenuItem(
              value: 'edit',
              child: Row(
                children: [
                  Icon(Icons.edit),
                  SizedBox(width: 8),
                  Text('编辑'),
                ],
              ),
            ),
            const PopupMenuItem(
              value: 'delete',
              child: Row(
                children: [
                  Icon(Icons.delete, color: Colors.red),
                  SizedBox(width: 8),
                  Text('删除', style: TextStyle(color: Colors.red)),
                ],
              ),
            ),
          ],
        ),
        onTap: () => controller.selectItem(item),
      ),
    );
  }

  Widget _buildErrorWidget(${className}Controller controller) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.error_outline,
            size: 64.w,
            color: Colors.red,
          ),
          SizedBox(height: 16.h),
          Text(
            '加载失败',
            style: TextStyle(
              fontSize: 18.sp,
              fontWeight: FontWeight.bold,
            ),
          ),
          SizedBox(height: 8.h),
          Text(
            controller.errorMessage,
            style: TextStyle(
              fontSize: 14.sp,
              color: Colors.grey[600],
            ),
            textAlign: TextAlign.center,
          ),
          SizedBox(height: 24.h),
          ElevatedButton(
            onPressed: controller.retry,
            child: const Text('重试'),
          ),
        ],
      ),
    );
  }

  Widget _buildEmptyWidget() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.inbox_outlined,
            size: 64.w,
            color: Colors.grey,
          ),
          SizedBox(height: 16.h),
          Text(
            '暂无数据',
            style: TextStyle(
              fontSize: 18.sp,
              fontWeight: FontWeight.bold,
            ),
          ),
          SizedBox(height: 8.h),
          Text(
            '点击右下角按钮添加新项目',
            style: TextStyle(
              fontSize: 14.sp,
              color: Colors.grey[600],
            ),
          ),
        ],
      ),
    );
  }

  void _showSearchDialog(BuildContext context, ${className}Controller controller) {
    showDialog(
      context: context,
      builder: (context) {
        final searchController = TextEditingController();
        return AlertDialog(
          title: const Text('搜索'),
          content: TextField(
            controller: searchController,
            decoration: const InputDecoration(
              hintText: '请输入搜索关键词',
              border: OutlineInputBorder(),
            ),
            onSubmitted: (value) {
              controller.searchItems(value);
              Navigator.pop(context);
            },
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('取消'),
            ),
            ElevatedButton(
              onPressed: () {
                controller.searchItems(searchController.text);
                Navigator.pop(context);
              },
              child: const Text('搜索'),
            ),
          ],
        );
      },
    );
  }

  void _showCreateDialog(BuildContext context, ${className}Controller controller) {
    final nameController = TextEditingController();
    final descriptionController = TextEditingController();

    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('创建新项目'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextField(
                controller: nameController,
                decoration: const InputDecoration(
                  labelText: '名称',
                  border: OutlineInputBorder(),
                ),
              ),
              SizedBox(height: 16.h),
              TextField(
                controller: descriptionController,
                decoration: const InputDecoration(
                  labelText: '描述',
                  border: OutlineInputBorder(),
                ),
                maxLines: 3,
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('取消'),
            ),
            ElevatedButton(
              onPressed: () {
                if (nameController.text.isNotEmpty) {
                  final item = ${isFullModule ? '${className}Entity' : className}(
                    id: DateTime.now().millisecondsSinceEpoch.toString(),
                    name: nameController.text,
                    description: descriptionController.text,
                    createdAt: DateTime.now(),${isFullModule ? '\n                    updatedAt: DateTime.now(),' : ''}
                  );
                  
                  controller.createItem(item);
                  Navigator.pop(context);
                }
              },
              child: const Text('创建'),
            ),
          ],
        );
      },
    );
  }

  void _showEditDialog(BuildContext context, ${className}Controller controller, ${isFullModule ? '${className}Entity' : className} item) {
    final nameController = TextEditingController(text: item.name);
    final descriptionController = TextEditingController(text: item.description);

    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('编辑项目'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextField(
                controller: nameController,
                decoration: const InputDecoration(
                  labelText: '名称',
                  border: OutlineInputBorder(),
                ),
              ),
              SizedBox(height: 16.h),
              TextField(
                controller: descriptionController,
                decoration: const InputDecoration(
                  labelText: '描述',
                  border: OutlineInputBorder(),
                ),
                maxLines: 3,
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('取消'),
            ),
            ElevatedButton(
              onPressed: () {
                if (nameController.text.isNotEmpty) {
                  final updatedItem = ${isFullModule ? '''${className}Entity(
                    id: item.id,
                    name: nameController.text,
                    description: descriptionController.text,
                    createdAt: item.createdAt,
                    updatedAt: DateTime.now(),
                  );''' : '''item.copyWith(
                    name: nameController.text,
                    description: descriptionController.text,
                  );'''}
                  
                  controller.updateItem(updatedItem);
                  Navigator.pop(context);
                }
              },
              child: const Text('保存'),
            ),
          ],
        );
      },
    );
  }

  void _showDeleteConfirmation(BuildContext context, ${className}Controller controller, ${isFullModule ? '${className}Entity' : className} item) {
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('确认删除'),
          content: Text('确定要删除"\${item.name}"吗？此操作不可撤销。'),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('取消'),
            ),
            ElevatedButton(
              onPressed: () {
                controller.deleteItem(item.id);
                Navigator.pop(context);
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.red,
              ),
              child: const Text('删除'),
            ),
          ],
        );
      },
    );
  }

  String _formatDate(DateTime date) {
    return '\${date.year}-\${date.month.toString().padLeft(2, '0')}-\${date.day.toString().padLeft(2, '0')}';
  }
}
''';
    
    BaseGenerator.writeFile('$basePath/presentation/pages/${BaseGenerator.toSnakeCase(className)}_page.dart', content);
  }

  static void _generateModuleWidgets(String className, String basePath) {
    // 生成一个示例组件
    final String widgetContent = BaseGenerator.generateFileHeader(
      '${className}Card',
      '${className}卡片组件'
    ) + '''
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../domain/entities/${BaseGenerator.toSnakeCase(className)}_entity.dart';

class ${className}Card extends StatelessWidget {
  final ${className}Entity item;
  final VoidCallback? onTap;
  final VoidCallback? onEdit;
  final VoidCallback? onDelete;

  const ${className}Card({
    Key? key,
    required this.item,
    this.onTap,
    this.onEdit,
    this.onDelete,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Card(
      margin: EdgeInsets.symmetric(vertical: 4.h),
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(8.r),
        child: Padding(
          padding: EdgeInsets.all(16.w),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Expanded(
                    child: Text(
                      item.name,
                      style: TextStyle(
                        fontSize: 16.sp,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  if (onEdit != null || onDelete != null)
                    PopupMenuButton<String>(
                      onSelected: (value) {
                        switch (value) {
                          case 'edit':
                            onEdit?.call();
                            break;
                          case 'delete':
                            onDelete?.call();
                            break;
                        }
                      },
                      itemBuilder: (context) => [
                        if (onEdit != null)
                          const PopupMenuItem(
                            value: 'edit',
                            child: Row(
                              children: [
                                Icon(Icons.edit),
                                SizedBox(width: 8),
                                Text('编辑'),
                              ],
                            ),
                          ),
                        if (onDelete != null)
                          const PopupMenuItem(
                            value: 'delete',
                            child: Row(
                              children: [
                                Icon(Icons.delete, color: Colors.red),
                                SizedBox(width: 8),
                                Text('删除', style: TextStyle(color: Colors.red)),
                              ],
                            ),
                          ),
                      ],
                    ),
                ],
              ),
              if (item.description.isNotEmpty) ...[
                SizedBox(height: 8.h),
                Text(
                  item.description,
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: Colors.grey[600],
                  ),
                ),
              ],
              SizedBox(height: 8.h),
              Text(
                '创建时间: \${_formatDate(item.createdAt)}',
                style: TextStyle(
                  fontSize: 12.sp,
                  color: Colors.grey[500],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  String _formatDate(DateTime date) {
    return '\${date.year}-\${date.month.toString().padLeft(2, '0')}-\${date.day.toString().padLeft(2, '0')}';
  }
}
''';
    
    BaseGenerator.writeFile('$basePath/presentation/widgets/${BaseGenerator.toSnakeCase(className)}_card.dart', widgetContent);
  }

  // ===== 简单模块生成方法 =====
  
  static String _generateSimpleModel(String className) {
    return BaseGenerator.generateFileHeader(
      className,
      '${className}简单模型'
    ) + '''
class $className {
  final String id;
  final String name;
  final String description;
  final DateTime createdAt;

  const $className({
    required this.id,
    required this.name,
    required this.description,
    required this.createdAt,
  });

  $className copyWith({
    String? id,
    String? name,
    String? description,
    DateTime? createdAt,
  }) {
    return $className(
      id: id ?? this.id,
      name: name ?? this.name,
      description: description ?? this.description,
      createdAt: createdAt ?? this.createdAt,
    );
  }

  @override
  String toString() {
    return '$className{id: \$id, name: \$name, description: \$description, createdAt: \$createdAt}';
  }
}
''';
  }

  static String _generateSimplePage(String className) {
    return BaseGenerator.generateFileHeader(
      '${className}Page',
      '${className}简单页面'
    ) + '''
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../models/${BaseGenerator.toSnakeCase(className)}.dart';

class ${className}Page extends StatefulWidget {
  const ${className}Page({Key? key}) : super(key: key);

  @override
  State<${className}Page> createState() => _${className}PageState();
}

class _${className}PageState extends State<${className}Page> {
  List<$className> _items = [];
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    _loadData();
  }

  Future<void> _loadData() async {
    setState(() => _isLoading = true);
    
    // 模拟数据加载
    await Future.delayed(const Duration(seconds: 1));
    
    setState(() {
      _items = [
        $className(
          id: '1',
          name: '示例项目1',
          description: '这是一个示例项目',
          createdAt: DateTime.now(),
        ),
        $className(
          id: '2',
          name: '示例项目2',
          description: '这是另一个示例项目',
          createdAt: DateTime.now(),
        ),
      ];
      _isLoading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('$className'),
        centerTitle: true,
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : _items.isEmpty
              ? _buildEmptyWidget()
              : ListView.builder(
                  padding: EdgeInsets.all(16.w),
                  itemCount: _items.length,
                  itemBuilder: (context, index) {
                    final item = _items[index];
                    return Card(
                      margin: EdgeInsets.only(bottom: 12.h),
                      child: ListTile(
                        title: Text(
                          item.name,
                          style: TextStyle(
                            fontSize: 16.sp,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        subtitle: Text(
                          item.description,
                          style: TextStyle(fontSize: 14.sp),
                        ),
                        onTap: () {
                          ScaffoldMessenger.of(context).showSnackBar(
                            SnackBar(content: Text('点击了: \${item.name}')),
                          );
                        },
                      ),
                    );
                  },
                ),
    );
  }

  Widget _buildEmptyWidget() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.inbox_outlined,
            size: 64.w,
            color: Colors.grey,
          ),
          SizedBox(height: 16.h),
          Text(
            '暂无数据',
            style: TextStyle(
              fontSize: 18.sp,
              fontWeight: FontWeight.bold,
            ),
          ),
        ],
      ),
    );
  }
}
''';
  }

  // ===== 文档和说明生成方法 =====
  
  static void _generateModuleReadme(String className, String moduleName, bool isFull, bool isSimple, bool withApi) {
    final String content = '''# $className 模块

${isFull ? '基于 Clean Architecture 架构的完整模块' : (isSimple ? '简单模块实现' : '标准模块实现')}

## 📁 目录结构

${_getModuleStructureDoc(moduleName, isFull, isSimple)}

## 🚀 功能特性

- ✅ **数据管理**: ${isFull ? 'Clean Architecture 分层架构' : '基础数据模型'}
- ✅ **状态管理**: ${isSimple ? '传统 StatefulWidget' : 'GetX 响应式状态管理'}
- ✅ **UI界面**: Material Design 风格界面
${withApi ? '- ✅ **网络请求**: 支持 API 数据获取' : ''}
${isFull ? '- ✅ **本地存储**: 支持离线数据缓存' : ''}
${isFull ? '- ✅ **用例模式**: 业务逻辑与表现层分离' : ''}

## 📝 使用方法

### 1. 路由配置

在 `lib/config/routes.dart` 中添加路由：

```dart
GetPage(
  name: '/${BaseGenerator.toKebabCase(className)}',
  page: () => const ${className}Page(),
  transition: Transition.rightToLeft,
),
```

### 2. 导航跳转

```dart
Get.toNamed('/${BaseGenerator.toKebabCase(className)}');
```

${isFull ? '''### 3. 依赖注入

在应用启动时注册依赖：

```dart
// 注册数据源
Get.lazyPut<${className}LocalDataSource>(
  () => ${className}LocalDataSourceImpl(Get.find<StorageService>()),
);

Get.lazyPut<${className}RemoteDataSource>(
  () => ${className}RemoteDataSourceImpl(Get.find<DioClient>()),
);

// 注册仓库
Get.lazyPut<${className}Repository>(
  () => ${className}RepositoryImpl(
    remoteDataSource: Get.find<${className}RemoteDataSource>(),
    localDataSource: Get.find<${className}LocalDataSource>(),
  ),
);

// 注册用例
Get.lazyPut(() => Get${className}List(Get.find<${className}Repository>()));
Get.lazyPut(() => Get${className}ById(Get.find<${className}Repository>()));
Get.lazyPut(() => Create$className(Get.find<${className}Repository>()));
Get.lazyPut(() => Update$className(Get.find<${className}Repository>()));
Get.lazyPut(() => Delete$className(Get.find<${className}Repository>()));
```''' : ''}

${!isSimple ? '''### ${isFull ? '4' : '3'}. 控制器使用

```dart
final controller = Get.find<${className}Controller>();

// 加载数据
await controller.loadItems();

// 创建项目
await controller.createItem(newItem);

// 更新项目
await controller.updateItem(updatedItem);

// 删除项目
await controller.deleteItem(itemId);

// 搜索项目
controller.searchItems('关键词');
```''' : ''}

## 🎯 架构说明

${isFull ? '''### Clean Architecture 分层

1. **Domain Layer (领域层)**
   - `entities/`: 业务实体
   - `repositories/`: 仓库接口
   - `usecases/`: 业务用例

2. **Data Layer (数据层)**
   - `models/`: 数据模型
   - `datasources/`: 数据源（本地/远程）
   - `repositories/`: 仓库实现

3. **Presentation Layer (表现层)**
   - `controllers/`: GetX 控制器
   - `pages/`: 页面组件
   - `widgets/`: 自定义组件''' : (isSimple ? '''### 简单架构

- `models/`: 数据模型
- `pages/`: 页面组件

适用于快速原型开发和简单功能模块。''' : '''### 标准架构

- `data/models/`: 数据模型
- `data/services/`: 服务层
- `presentation/controllers/`: 控制器
- `presentation/pages/`: 页面组件
- `presentation/widgets/`: 自定义组件

平衡了复杂度和功能性，适用于大多数业务场景。''')}

## 🔧 自定义扩展

### 添加新字段

${isFull ? '''1. 更新 Entity:
```dart
abstract class ${className}Entity {
  // 添加新字段
  final String newField;
  
  const ${className}Entity({
    // 现有字段...
    required this.newField,
  });
}
```

2. 更新 Model:
```dart
class ${className}Model extends ${className}Entity {
  // 更新构造函数和 JSON 序列化方法
}
```''' : '''1. 更新模型:
```dart
class $className {
  // 添加新字段
  final String newField;
  
  const $className({
    // 现有字段...
    required this.newField,
  });
}
```'''}

### 添加新功能

${!isSimple ? '''1. 在控制器中添加新方法
2. 在页面中添加对应的 UI
3. 更新路由配置（如需要）''' : '''1. 在页面状态类中添加新方法
2. 在页面中添加对应的 UI
3. 更新模型类（如需要）'''}

## 📚 相关文档

- [GetX 状态管理](https://pub.dev/packages/get)
- [Flutter ScreenUtil](https://pub.dev/packages/flutter_screenutil)
${isFull ? '- [Clean Architecture](https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html)' : ''}
${withApi ? '- [Dio 网络请求](https://pub.dev/packages/dio)' : ''}

---

💡 **提示**: 这是一个${isFull ? '完整的' : (isSimple ? '简单的' : '标准的')}模块模板，可以根据具体业务需求进行定制和扩展。
''';
    
    BaseGenerator.writeFile('lib/features/$moduleName/README.md', content);
  }

  static String _getModuleStructureDoc(String moduleName, bool isFull, bool isSimple) {
    if (isFull) {
      return '''```
lib/features/$moduleName/
├── data/
│   ├── datasources/
│   │   ├── ${moduleName}_local_datasource.dart
│   │   └── ${moduleName}_remote_datasource.dart
│   ├── models/
│   │   └── ${moduleName}_model.dart
│   └── repositories/
│       └── ${moduleName}_repository_impl.dart
├── domain/
│   ├── entities/
│   │   └── ${moduleName}_entity.dart
│   ├── repositories/
│   │   └── ${moduleName}_repository.dart
│   └── usecases/
│       ├── create_${moduleName}.dart
│       ├── delete_${moduleName}.dart
│       ├── get_${moduleName}_by_id.dart
│       ├── get_${moduleName}_list.dart
│       └── update_${moduleName}.dart
├── presentation/
│   ├── controllers/
│   │   └── ${moduleName}_controller.dart
│   ├── pages/
│   │   └── ${moduleName}_page.dart
│   └── widgets/
│       └── ${moduleName}_card.dart
└── README.md
```''';
    } else if (isSimple) {
      return '''```
lib/features/$moduleName/
├── models/
│   └── ${moduleName}.dart
├── pages/
│   └── ${moduleName}_page.dart
└── README.md
```''';
    } else {
      return '''```
lib/features/$moduleName/
├── data/
│   ├── models/
│   │   └── ${moduleName}.dart
│   └── services/
│       └── ${moduleName}_service.dart
├── presentation/
│   ├── controllers/
│   │   └── ${moduleName}_controller.dart
│   ├── pages/
│   │   └── ${moduleName}_page.dart
│   └── widgets/
└── README.md
```''';
    }
  }

  static void _printModuleStructure(String moduleName, bool isFull, bool isSimple) {
    print('\n📁 模块结构:');
    print(_getModuleStructureDoc(moduleName, isFull, isSimple));
  }

  static void _printUsageInstructions(String className, String moduleName, bool isFull, bool isSimple, bool withApi) {
    print('\n📋 使用说明:');
    
    print('1. 添加路由配置:');
    print('   GetPage(');
    print('     name: \'/${BaseGenerator.toKebabCase(className)}\',');
    print('     page: () => const ${className}Page(),');
    print('   ),');
    
    print('');
    print('2. 导航到模块:');
    print('   Get.toNamed(\'/${BaseGenerator.toKebabCase(className)}\');');

    if (isFull) {
      print('');
      print('3. 注册依赖 (在 main.dart):');
      print('   // 详见模块 README.md 中的依赖注入部分');
    }

    if (!isSimple) {
      print('');
      print('${isFull ? '4' : '3'}. 获取控制器:');
      print('   final controller = Get.find<${className}Controller>();');
    }

    print('');
    print('📖 更多信息请查看: lib/features/$moduleName/README.md');
  }
}
''';
  }
}